package com.study.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;

import org.springframework.util.StringUtils;

import com.study.io.util.HostInfo;

public class BIOEchoClient {

	public static void main(String[] args) throws Exception {

		new Thread(() -> {
			try {
				Socket socket = new Socket(HostInfo.HOST_NAME, HostInfo.PORT);
				BufferedReader KEYBOARD_INPUT = new BufferedReader(new InputStreamReader(System.in));
				String readLine = null;
				PrintStream out = new PrintStream(socket.getOutputStream());
				while (true) {
					while(true){
						System.out.print("please input：");
						readLine = KEYBOARD_INPUT.readLine();
						if(!StringUtils.isEmpty(readLine)){
							break;
						}
					}
					
					try {
						
//						socket.getOutputStream().write(
//								("helloworld...").getBytes());
//						socket.getOutputStream().flush();
//						socket.getOutputStream().close();
						
						System.out.println("readLine: " + readLine);
						socket.getOutputStream().write(
								(readLine + "\n").getBytes());
						socket.getOutputStream().flush();   //这里无法flush 到服务端 ，服务端没有收到消息，的原因是 没有结束符"\n"
						if(readLine.equalsIgnoreCase("byebye")){
							break;
						}
						//out.println(readLine);
						Scanner scanner = new Scanner(socket.getInputStream());
						if(scanner.hasNext()){
							String str = scanner.next();
							System.out.println(str);
						}
						
//						int len =0 ;
//						byte [] data = new byte[1024];
//						while ((len = socket.getInputStream().read(data)) != -1) {
//							//socket.getOutputStream().write(new StringBuffer("[ECHO]" + new String(data)).toString().getBytes());
//							System.out.println(new String(data, 0, len));
//
//						}

						//Thread.sleep(2000);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}).start();

	}
}
